//
//  HttpUtil.m
//  网络请求(GET&POST) -> TZJ
//
//  Created by My Mac on 2017/4/17.
//  Copyright © 2017年 My Mac. All rights reserved.
//

#import "HttpUtil.h"

@implementation HttpUtil

+(void)requestWithURLString:(NSString *)urlString httpMethod:(NSString *)method httpBody:(NSMutableDictionary *)httpBody handler:(void (^)(id _Nullable))value
{
    /**
     * 字符转译,比如url中有汉字或者空格,则需要转译
     * NSCharacterSet: 字符集
     * URLQueryAllowedCharacterSet: 查询允许的字符集
     */
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //网络地址
    NSURL *url = [NSURL URLWithString:urlString];
    
    //网络请求(默认GET请求)(POST请求要用可变的request:NSMutableURLRequest)
    //所以这里用一个通用的：NSMutableURLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //发送请求类型
    request.HTTPMethod = method;
    //[method uppercaseString] 将字符串全部转为大写
    if([[method uppercaseString] isEqualToString:@"POST"]){
        //设置请求体数据,将传入的参数转为json数据
        request.HTTPBody = [NSJSONSerialization dataWithJSONObject:httpBody options:NSJSONWritingPrettyPrinted error:nil];
    }
    //网络会话
    NSURLSession *session = [NSURLSession sharedSession];
    //创建任务
    NSURLSessionDataTask *sdTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        //更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调
            value(dict);
        });
    }];
    
    [sdTask resume];
}

@end
